﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Wolfy.NetDisk.Core.Service;
using Wolfy.NetDisk.Core.Model;
using System.IO;
using Wolfy.NetDisk.Core.Security;
using Newtonsoft.Json;
using Wolfy.NetDisk.Site.Models;
namespace Wolfy.NetDisk.Site.Controllers
{
    public class NetdiskController : BaseController
    {
        private readonly IFileService fileService;
        private readonly IFolderService folderService;
        public NetdiskController(
            IUserService userService,
            INavigationService navigationService,
            IImageManagerService imageManagerService,
            IFileService fileService,
            IFolderService folderService,
            IIconService iconService,
            ILogService logService)
            : base(userService, navigationService, imageManagerService, logService, iconService)
        {
            this.fileService = fileService;
            this.folderService = folderService;
        }
        [HttpPost]

        public JsonResult PostedFile()
        {
            var file = HttpContext.Request.Files[0];
            var fileRelativePath = HttpContext.Request["path"];
            if (file == null)
            {
                return new JsonResult { Data = new { _msg = "没有选择文件", _code = 503 }, JsonRequestBehavior = JsonRequestBehavior.DenyGet };
            }
            string fileName = Path.GetFileName(file.FileName);
            string fileExt = Path.GetExtension(file.FileName);
            string fileNameWithoutExt = Path.GetFileNameWithoutExtension(file.FileName);
            var currentUser = userService.Where(x => x.UserName == User.Identity.Name).FirstOrDefault();
            try
            {


                string fileMD5 = MD5Hleper.GetMD5FromFile(file.InputStream);
                long haveUsedSize = currentUser.Files.Sum(x => x.Size);
                long fileSize = file.InputStream.Length;
                if (haveUsedSize + fileSize > currentUser.NetDiskSize)
                {
                    return new JsonResult { Data = new { _msg = "网盘空间已满，请删除部分文件后再进行上传或者申请网盘扩容。", _code = 503 }, JsonRequestBehavior = JsonRequestBehavior.DenyGet };
                }
                string newFileName = fileMD5 + fileExt;
                string fileSaveDir = Server.MapPath("~/NetDisk/" + User.Identity.Name + fileRelativePath);
                if (!Directory.Exists(fileSaveDir))
                {
                    Directory.CreateDirectory(fileSaveDir);
                }
                string fileSavePath = Path.Combine(fileSaveDir, newFileName);
                //如果存在则不再保存物理文件，直接修改数据库
                if (!System.IO.File.Exists(fileSavePath))
                {
                    file.SaveAs(fileSavePath);
                }

                //获取图标
                var icon = iconService.Where(x => x.Ext == fileExt).FirstOrDefault();
                //如果没有找到图标则使用默认图标
                if (icon == null)
                {
                    icon = iconService.Where(x => x.Ext == ".other").FirstOrDefault();
                }
                //查找所在的文件夹
                Folder folder = folderService.Where(x => x.Path == fileRelativePath && x.IsDeleted == false && x.User.Id == currentUser.Id).FirstOrDefault();
                //根目录不存在则创建
                if (folder == null)
                {
                    int mainId = iconService.Create(new Icon { Path = "/Content/Images/main.png", IsDeleted = false, Dt = DateTime.Now, Ext = ".main" });
                    var myDiskIcon = iconService.Get(mainId);
                    int myDiskFolderId = folderService.Create(new Folder { ParentFolder = null, Name = "我的网盘", Icon = myDiskIcon, Folders = null, Files = null, Dt = DateTime.Now, Path = "/", IsDeleted = false, User = currentUser });
                    folder = folderService.Get(myDiskFolderId);
                }
                //保存数据库
                var saveDbFile = new Core.Model.File
                {
                    Icon = icon,
                    Md5 = fileMD5,
                    Name = fileName,
                    IsDeleted = false,
                    Folder = folder,
                    Path = Path.Combine(fileRelativePath, fileName),
                    Dt = DateTime.Now,
                    Size = fileSize,
                    User = currentUser,
                    Ext = fileExt
                };
                //判断文件是否已经存在了
                int count = fileService.HowManyFileExists(saveDbFile, currentUser);
                if (count > 0)
                {
                    saveDbFile.Name = fileNameWithoutExt + string.Format("({0}){1}", count + 1, fileExt);
                }
                int fileId = fileService.Create(saveDbFile);
                saveDbFile.Id = fileId;
                logService.WriteLog(new Log { IsDeleted = false, LogType = LogType.Info, Conent = string.Format("上传文件 [{0}]", fileName), Op = "PostedFile", User = currentUser, Dt = DateTime.Now });
                return new JsonResult
                {
                    Data = JsonConvert.SerializeObject(new
                    {
                        _msg = "上传成功",
                        _code = 200,
                        _data = new { file = new FileViewModel { Id = saveDbFile.Id, Dt = saveDbFile.Dt.ToString("yyyy/MM/dd HH:mm:ss"), Icon = icon.Path, Name = saveDbFile.Name, Path = saveDbFile.Path, Size = (saveDbFile.Size * 1.0).ToMB() } }
                    }),
                    JsonRequestBehavior = JsonRequestBehavior.DenyGet
                };
            }
            catch (Exception ex)
            {
                logService.WriteLog(new Log { Dt = DateTime.Now, Conent = string.Format("上传文件失败:{0},{1}", fileName, ex.Message), User = currentUser, Op = "PostedFile", LogType = LogType.Error, IsDeleted = false });
                return new JsonResult { Data = new { _msg = "上传文件失败，请重新尝试。", _code = 500 }, JsonRequestBehavior = JsonRequestBehavior.DenyGet };

            }
        }
    }
}